package controller

import (
	"net/http"

	"gitee.com/shiwjlinux/blog-web/db"
	"gitee.com/shiwjlinux/blog-web/util"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func ModifyUserInfo(c *gin.Context) {
	claim, _ := util.ParseToken(c.GetHeader("token"))
	name := claim.Name
	user := db.User{}

	db.DB.Where("name=?", name).First(&user)
	c.ShouldBind(&user)
	db.DB.Save(&user)

	c.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

func ModifyPassword(c *gin.Context) {
	claim, _ := util.ParseToken(c.GetHeader("token"))
	name := claim.Name

	form := struct {
		OldPassword string
		NewPassword string
	}{}

	c.ShouldBind(&form)

	user := util.AuthUserAndPassword(name, form.OldPassword)
	if user == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "密码错误",
		})
		return
	}

	user.Password, _ = util.HashPassword(form.NewPassword)
	db.DB.Save(&user)

	c.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

func ModifyArticle(c *gin.Context) {
	data := db.Article{}
	c.ShouldBindBodyWith(&data, binding.JSON)

	claim, _ := util.ParseToken(c.GetHeader("token"))
	name := claim.Name

	article := db.GetArticle(data.ID)
	if article.UserID != db.GetUserByName(name).ID {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "没有权限",
		})
		return
	}

	// 修改分类
	db.DB.Where("article_id=?", article.ID).Delete(&db.ArticleCategory{})
	db.DB.Create(&db.ArticleCategory{
		ArticleID:  article.ID,
		CategoryID: data.CategoryID,
	})

	// 修改标签
	db.DB.Where("article_id=?", article.ID).Delete(&db.ArticleTag{})

	for _, ID := range data.Tags {
		db.DB.Create(&db.ArticleTag{
			ArticleID: article.ID,
			TagID:     ID,
		})
	}

	c.ShouldBindBodyWith(&article, binding.JSON)
	db.DB.Save(&article)

	c.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
		"ID":  article.ID,
	})
}
